package javango.forms.fields;

import java.util.Map;

import com.google.inject.Inject;

import javango.forms.widgets.ChoicesWidget;
import javango.forms.widgets.SelectWidget;
import javango.forms.widgets.Widget;
import javango.forms.widgets.WidgetFactory;

public class LongChoiceField extends LongField implements ChoiceField {

	private Map<String, Object> choices;
	
	public LongChoiceField(WidgetFactory widgetFactory, Map<String, Object> choices) {
		super(widgetFactory);
		setChoices(choices);
		this.setWidget(SelectWidget.class);
	}
	
	@Inject
	public LongChoiceField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		this.setWidget(SelectWidget.class);
	}

	public long getChoiceCount() {
		return choices.size();
	}
	
	public Map<String, Object> getChoices() {
		return choices;
	}

	public LongChoiceField setChoices(Map<String, Object> choices) {
		this.choices = choices;
		return this;
	}	
	
	public Object getByKey(String key) {
		if (choices == null) {
			return null;
		}
		return choices.get(key);
	}

	@Override
	public Widget getWidget() {
		Widget w = super.getWidget();
		if (w instanceof ChoicesWidget) {
			((ChoicesWidget)w).setField(this);			
		}
		return w;
	}

	@Override
	public Object clean(String[] value, Map<String, String> errors) {
		Object myValue = super.clean(value, errors);
		if (choices == null) {
			errors.put(this.name, "Select a valid choice.  That choice is not one of the available choices. No choices are available");
		} else if (!choices.containsKey(myValue)) {
			errors.put(this.name, "Select a valid choice.  That choice is not one of the available choices.");
		}
		
		return myValue;
	}
	

}
